package com.jy.fxf_phone.utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by JY on 2016/10/25.
 */

public class MyTimer {
    Timer timer;
    TimerTask timerTask;
    long i;
    boolean isStart = false;
    OnTimerListener onTimerListener;

    private static class MyTimerHolder {
        static final MyTimer INSTANCE = new MyTimer();
    }

    public static MyTimer getInstance() {
        return MyTimerHolder.INSTANCE;
    }

    private MyTimer() {
    }

    /**
     * 开始计时
     *
     * @param restart 是否重头计时
     */
    public void start(boolean restart) {
        if (restart) {
            i = 0;
        }
        if (timer != null && timerTask != null) {
            timer.cancel();
            timerTask.cancel();
            isStart = false;
        }
        timer = new Timer(true);
        timerTask = new TimerTask() {
            @Override
            public void run() {
                onTimerListener.onTimerListener(i);
                i++;
            }
        };
        if (!isStart) {
            timer.schedule(timerTask, 0, 1000);
            isStart = true;
        }
    }

    public void setOnTimerListener(OnTimerListener onTimerListener) {
        this.onTimerListener = onTimerListener;
    }

    public void stop() {
        if (timer != null && timerTask != null) {
            timer.cancel();
            timerTask.cancel();
            isStart = false;
        }
    }
}
